package com.my.screenadapter;

import android.content.Context;
import android.graphics.Color;
import android.os.Environment;
import android.os.SystemClock;
//import android.support.compat.*;
//import android.support.design.widget.Snackbar;
//import android.support.multidex.MultiDex;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import androidx.multidex.MultiDex;

import com.tencent.bugly.crashreport.CrashReport;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.litepal.LitePal;
import org.litepal.LitePalApplication;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;

import cn.jpush.android.api.JPushInterface;
import de.mindpipe.android.logging.log4j.LogConfigurator;

/**
 * Created by 张英杰 on 2016/12/5.
 */
public class MyApplication extends LitePalApplication {

    private Logger logger = Logger.getLogger(MyApplication.class);
    private static final String TAG = "MyApplication";
    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(TAG, "onCreate: ---->"+this);
        instance = this;
        LitePal.initialize(this);
        setBugly(this);
        Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(Thread t, Throwable e) {
                CrashReport.postCatchedException(e);
                if (logger != null) {
                    StringWriter sw = new StringWriter();
                    e.printStackTrace(new PrintWriter(sw, true));
                    logger.error(" uncaughtException ======= " + sw.toString());
                }

                SystemClock.sleep(4000);
                android.os.Process.killProcess(android.os.Process.myPid());
            }
        });
        configLog();

        initSmartToastAndSnackbar();

        if (BuildConfig.DEBUG) {//极光推送
            JPushInterface.setDebugMode(true); 	// 设置开启日志,发布时请关闭日志
        }else {
            JPushInterface.setDebugMode(false); 	// 设置开启日志,发布时请关闭日志
        }
        JPushInterface.init(MyApplication.getContext());     		// 初始化 JPush

    }

    private static MyApplication instance;
    public static MyApplication getInstance(){
        return instance;
    }
    private void setBugly(Context context) {
        // 获取当前包名
        String packageName = context.getPackageName();
        // 获取当前进程名
        String processName = getProcessName(android.os.Process.myPid());
        // 设置是否为上报进程
        CrashReport.UserStrategy strategy = new CrashReport.UserStrategy(context);
        strategy.setUploadProcess(processName == null || processName.equals(packageName));
        // 初始化Bugly
        //第三个参数为SDK调试模式开关，调试模式的行为特性如下：
        // 输出详细的Bugly SDK的Log；
        //每一条Crash都会被立即上报；
        //自定义日志将会在Logcat中输出。
        //建议在测试阶段建议设置成true，发布时设置为false。
//        CrashReport.initCrashReport(context, "b9d059be1d", BuildConfig.DEBUG, strategy);
        CrashReport.initCrashReport(context, "1200d62e04", true, strategy);

        CrashReport.putUserData(context, "serialNo" ,android.os.Build.SERIAL);

    }

    private void configLog() {
        Log.i("app isSdcardMounted", Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())+"");

//        String fileFolder = "/storage/sdcard0/face_rec/crash/oids_normal";
        String fileFolder =getFilesDir().getAbsolutePath();
        File file = new File(fileFolder);
        if (!file.exists()){
            file.mkdirs();
        }
//        totalFile = logPathApplication + File.separator + "OPZOON" + File.separator + "logs"
//                + File.separator + fileName;

        String fileName = "log.log";
        String totalFile = fileFolder + File.separator + "logs"
                + File.separator + fileName;

        Log.w(this.getClass().getSimpleName(),"log address=="+totalFile);
        LogConfigurator logConfigurator = new LogConfigurator();
        logConfigurator.setFileName(totalFile);//设置输入日志位置
        logConfigurator.setRootLevel(Level.DEBUG); //默认就是 debug
//        logConfigurator.setLevel("org.apache", Level.ERROR);
        logConfigurator.setLevel("org.apache", Level.INFO);//todo 018-7-12 19:45:43 测试对比Error 没有影响Error没有少打印信息
        logConfigurator.setFilePattern("%d %-5p [%c{2}]-[%L] %m%n");
        logConfigurator.setMaxFileSize(1024 * 1024 * 10);
        logConfigurator.setMaxBackupSize(10);
        logConfigurator.setImmediateFlush(true);
        logConfigurator.configure();
    }

    /**
     * 获取进程号对应的进程名
     *
     * @param pid 进程号
     * @return 进程名
     */
    private static String getProcessName(int pid) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader("/proc/" + pid + "/cmdline"));
            String processName = reader.readLine();
            if (!TextUtils.isEmpty(processName)) {
                processName = processName.trim();
            }
            return processName;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException exception) {
                exception.printStackTrace();
            }
        }
        return null;
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        long startTime = System.currentTimeMillis();
        Log.i(TAG, "attachBaseContext: ");
        MultiDex.install(this);
        Log.i(TAG, "attachBaseContext: MultiDex.install speed time "+(System.currentTimeMillis()-startTime));
    }

    private void initSmartToastAndSnackbar() {

    }

    @Override
    public void onTerminate() {
        super.onTerminate();

    }
}

